<?php
/**
 * 工作流审批控制器
 * 处理审批相关的HTTP请求
 */

declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use app\service\WorkflowService;
use think\facade\Request;
use think\response\Json;

class WorkflowController extends BaseController
{
    protected $workflowService;

    public function __construct(\think\App $app)
    {
        parent::__construct($app);
        $this->workflowService = new WorkflowService();
    }

    /**
     * 获取我的待审批列表
     * @return Json
     */
    public function myPendingApprovals(): Json
    {
        try {
            $userId = $this->getUserId();
            if ($userId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            $params = Request::param();
            $result = $this->workflowService->getPendingApprovals($userId, $params);

            return $this->paginate(
                $result['list'],
                $result['total'],
                $result['page'],
                $result['limit'],
                '获取待审批列表成功'
            );
        } catch (\Exception $e) {
            return $this->error('获取待审批列表失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取审批详情
     * @return Json
     */
    public function approvalDetail(): Json
    {
        try {
            $params = Request::param();
            $approvalId = (int)($params['id'] ?? 0);

            if ($approvalId <= 0) {
                return $this->paramError('审批ID不能为空');
            }

            $userId = $this->getUserId();
            if ($userId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            $detail = $this->workflowService->getApprovalDetail($approvalId);

            return $this->success($detail, '获取审批详情成功');
        } catch (\Exception $e) {
            return $this->error('获取审批详情失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 处理审批
     * @return Json
     */
    public function processApproval(): Json
    {
        try {
            $params = Request::param();
            $approvalId = (int)($params['approval_id'] ?? 0);
            $action = (int)($params['action'] ?? 0);
            $remark = trim($params['remark'] ?? '');

            if ($approvalId <= 0) {
                return $this->paramError('审批ID不能为空');
            }

            if (!in_array($action, [WorkflowService::STATUS['APPROVED'], WorkflowService::STATUS['REJECTED']])) {
                return $this->paramError('审批动作无效');
            }

            $userId = $this->getUserId();
            if ($userId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            $this->workflowService->processApproval($approvalId, $userId, $action, $remark);

            $actionText = $action == WorkflowService::STATUS['APPROVED'] ? '通过' : '拒绝';
            return $this->success('审批' . $actionText . '成功');
        } catch (\Exception $e) {
            return $this->error('审批处理失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 创建审批流程（供其他业务模块调用）
     * @return Json
     */
    public function createApproval(): Json
    {
        try {
            $params = Request::param();
            
            $type = $params['type'] ?? '';
            $businessId = (int)($params['business_id'] ?? 0);
            $title = trim($params['title'] ?? '');
            $approvers = $params['approvers'] ?? [];
            $content = $params['content'] ?? [];

            if (empty($type)) {
                return $this->paramError('审批类型不能为空');
            }

            if ($businessId <= 0) {
                return $this->paramError('业务记录ID不能为空');
            }

            if (empty($title)) {
                return $this->paramError('审批标题不能为空');
            }

            if (empty($approvers) || !is_array($approvers)) {
                return $this->paramError('审批人不能为空');
            }

            $applicantId = $this->getUserId();
            if ($applicantId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            $approvalId = $this->workflowService->createApproval(
                $type,
                $businessId,
                $applicantId,
                $approvers,
                $title,
                $content
            );

            return $this->created(['approval_id' => $approvalId], '审批流程创建成功');
        } catch (\Exception $e) {
            return $this->error('创建审批流程失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取支持的审批类型
     * @return Json
     */
    public function approvalTypes(): Json
    {
        try {
            $types = [];
            foreach (WorkflowService::APPROVAL_TYPES as $key => $name) {
                $types[] = [
                    'value' => $key,
                    'label' => $name
                ];
            }

            return $this->success($types, '获取审批类型成功');
        } catch (\Exception $e) {
            return $this->error('获取审批类型失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取审批统计数据
     * @return Json
     */
    public function approvalStatistics(): Json
    {
        try {
            $userId = $this->getUserId();
            if ($userId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            // 获取待审批数量统计
            $pendingStats = [];
            foreach (WorkflowService::APPROVAL_TYPES as $type => $typeName) {
                $count = \think\facade\Db::name('workflow_approval_step')
                    ->alias('s')
                    ->join('workflow_approval a', 's.approval_id = a.id')
                    ->where('s.approver_id', $userId)
                    ->where('s.status', WorkflowService::STATUS['PENDING'])
                    ->where('a.type', $type)
                    ->where('a.status', 'in', [WorkflowService::STATUS['PENDING'], WorkflowService::STATUS['PROCESSING']])
                    ->count();

                if ($count > 0) {
                    $pendingStats[] = [
                        'type' => $type,
                        'type_name' => $typeName,
                        'count' => $count
                    ];
                }
            }

            // 总待审批数量
            $totalPending = \think\facade\Db::name('workflow_approval_step')
                ->alias('s')
                ->join('workflow_approval a', 's.approval_id = a.id')
                ->where('s.approver_id', $userId)
                ->where('s.status', WorkflowService::STATUS['PENDING'])
                ->where('a.status', 'in', [WorkflowService::STATUS['PENDING'], WorkflowService::STATUS['PROCESSING']])
                ->count();

            return $this->success([
                'total_pending' => $totalPending,
                'pending_by_type' => $pendingStats
            ], '获取审批统计成功');
        } catch (\Exception $e) {
            return $this->error('获取审批统计失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取我发起的审批列表
     * @return Json
     */
    public function myApprovals(): Json
    {
        try {
            $userId = $this->getUserId();
            if ($userId <= 0) {
                return $this->error('未登录或登录已过期', 401);
            }

            $params = Request::param();
            $page = (int)($params['page'] ?? 1);
            $limit = (int)($params['limit'] ?? 10);

            $where = [];
            $where[] = ['applicant_id', '=', $userId];

            // 类型筛选
            if (!empty($params['type'])) {
                $where[] = ['type', '=', $params['type']];
            }

            // 状态筛选
            if (isset($params['status']) && $params['status'] !== '') {
                $where[] = ['status', '=', (int)$params['status']];
            }

            $list = \think\facade\Db::name('workflow_approval')
                ->where($where)
                ->page($page, $limit)
                ->order('create_time', 'desc')
                ->select()
                ->each(function($item) {
                    $item['type_name'] = WorkflowService::APPROVAL_TYPES[$item['type']] ?? $item['type'];
                    $item['status_name'] = $this->getStatusName($item['status']);
                    $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                    $item['content'] = $item['content'] ? json_decode($item['content'], true) : [];
                    return $item;
                })
                ->toArray();

            $total = \think\facade\Db::name('workflow_approval')
                ->where($where)
                ->count();

            return $this->paginate($list, $total, $page, $limit, '获取我发起的审批列表成功');
        } catch (\Exception $e) {
            return $this->error('获取我发起的审批列表失败: ' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取状态名称
     * @param int $status
     * @return string
     */
    private function getStatusName(int $status): string
    {
        $statusNames = [
            WorkflowService::STATUS['PENDING'] => '待审批',
            WorkflowService::STATUS['PROCESSING'] => '审批中',
            WorkflowService::STATUS['APPROVED'] => '已通过',
            WorkflowService::STATUS['REJECTED'] => '已拒绝',
            WorkflowService::STATUS['CANCELLED'] => '已取消'
        ];

        return $statusNames[$status] ?? '未知状态';
    }
}